<template>
  <div class="room-price-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>房间价格管理</span>
          <el-button type="primary" @click="handleBatchUpdate"
            >批量更新</el-button
          >
        </div>
      </template>
      <el-calendar @input="updateCalendarData">
        <template #date-cell="{ data }">
          <div @dblclick="handleCellDblClick(data.day)">
            <p class="date" :class="data.isSelected ? 'is-selected' : ''">
              {{ data.day.split("-").slice(1).join("-") }}
              <!-- {{ data.isSelected ? "✔️" : "" }} -->
            </p>
            <calendar-cell
              :date="data.day.split('-').slice(2).join('-')"
              :prices="prices[data.day]"
              :room-type-map="roomTypeMap"
            />
          </div>
        </template>
      </el-calendar>
    </el-card>

    <el-drawer
      v-model="drawerVisible"
      title="修改房型价格"
      :size="400"
      :with-header="true"
    >
      <div class="drawer-content">
        <div v-if="selectedDate" class="selected-date">
          选中日期：{{ selectedDate }}
        </div>
        <div v-for="type in roomTypes" :key="type.typeId" class="price-item">
          <el-form :model="editingPrices[type.typeId]" label-width="100px">
            <el-form-item :label="type.typeName">
              <el-input-number
                v-model="editingPrices[type.typeId]"
                :min="0"
                :step="10"
                :precision="2"
              />
            </el-form-item>
          </el-form>
        </div>
        <div class="drawer-footer">
          <el-button @click="drawerVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSavePrice">保存</el-button>
        </div>
      </div>
    </el-drawer>
    <el-dialog v-model="dialogVisible" title="批量更新房型价格" width="500px">
      <el-form :model="batchUpdateForm" label-width="100px">
        <el-form-item label="起始日期">
          <el-date-picker
            v-model="batchUpdateForm.startDate"
            type="date"
            placeholder="选择起始日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="结束日期">
          <el-date-picker
            v-model="batchUpdateForm.endDate"
            type="date"
            placeholder="选择结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <div v-for="type in roomTypes" :key="type.typeId" class="price-item">
          <el-form-item :label="type.typeName">
            <el-input-number
              v-model="batchUpdateForm.prices[type.typeId]"
              :min="0"
              :step="10"
              :precision="2"
            />
          </el-form-item>
        </div>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleBatchSave">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from "vue";
import CalendarCell from "./components/CalendarCell.vue";
import { ElMessage } from "element-plus";
import {
  getRoomTypeList,
  type RoomType,
  getRoomPriceByTime,
  updateRoomPrice,
  updateRoomPriceByDateRange
} from "@/api/room";

defineOptions({
  name: "RoomPrice"
});

const roomTypes = ref<RoomType[]>([]);
const roomTypeMap = ref<Map<number, string>>(new Map());
const prices = ref<Record<string, any>>({});

const drawerVisible = ref(false);
const selectedDate = ref<string>("");
const editingPrices = ref<Record<number, number>>({});

const fetchRoomTypes = async () => {
  try {
    const response = await getRoomTypeList();
    if (response.data) {
      roomTypes.value = response.data;
      roomTypes.value.forEach(type => {
        roomTypeMap.value.set(type.typeId, type.typeName);
      });
    }
  } catch (error) {
    console.error("获取房型列表失败:", error);
  }
};

const fetchPrices = async (startDate: string, endDate: string) => {
  try {
    const response = await getRoomPriceByTime(startDate, endDate);
    if (response.data) {
      const newPrices: Record<string, any> = {};
      response.data.forEach(dailyPrice => {
        newPrices[dailyPrice.date] = dailyPrice;
      });
      prices.value = newPrices;
    }
  } catch (error) {
    console.error("获取房价数据失败:", error);
  }
};

const updateCalendarData = async (date: Date) => {
  // 获取当前月份的第一天和最后一天
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const firstDay = `${year}-${month.toString().padStart(2, "0")}-01`;

  // 获取月份的最后一天
  const lastDate = new Date(year, month, 0);
  const lastDay = `${year}-${month.toString().padStart(2, "0")}-${lastDate.getDate().toString().padStart(2, "0")}`;

  console.log("获取价格区间:", firstDay, lastDay);
  await fetchPrices(firstDay, lastDay);
};

const handleCellDblClick = (date: string) => {
  selectedDate.value = date;
  drawerVisible.value = true;

  // 初始化编辑价格
  editingPrices.value = {};
  const dailyPrice = prices.value[date];
  if (dailyPrice?.roomPrices) {
    dailyPrice.roomPrices.forEach((price: any) => {
      editingPrices.value[price.roomTypeId] = price.price;
    });
  }

  // 确保所有房型都有初始价格
  roomTypes.value.forEach(type => {
    if (!(type.typeId in editingPrices.value)) {
      editingPrices.value[type.typeId] = type.basePrice;
    }
  });
};

const handleSavePrice = async () => {
  try {
    for (const [typeId, price] of Object.entries(editingPrices.value)) {
      await updateRoomPrice({
        roomTypeId: parseInt(typeId),
        price: price,
        date: selectedDate.value
      });
    }

    // 重新获取当前月份的价格数据
    const date = new Date(selectedDate.value);
    await updateCalendarData(date);

    ElMessage.success("价格更新成功");
    drawerVisible.value = false;
  } catch (error) {
    console.error("更新房价失败:", error);
    ElMessage.error("更新房价失败");
  }
};

const dialogVisible = ref(false);
const batchUpdateForm = ref({
  startDate: "",
  endDate: "",
  prices: {} as Record<number, number>
});

const handleBatchUpdate = () => {
  batchUpdateForm.value.prices = {};
  roomTypes.value.forEach(type => {
    batchUpdateForm.value.prices[type.typeId] = type.basePrice;
  });
  dialogVisible.value = true;
};

const handleBatchSave = async () => {
  if (!batchUpdateForm.value.startDate || !batchUpdateForm.value.endDate) {
    ElMessage.warning("请选择起始日期和结束日期");
    return;
  }

  try {
    for (const [typeId, price] of Object.entries(
      batchUpdateForm.value.prices
    )) {
      await updateRoomPriceByDateRange(
        batchUpdateForm.value.startDate,
        batchUpdateForm.value.endDate,
        {
          roomTypeId: parseInt(typeId),
          price: price,
          date: batchUpdateForm.value.startDate
        }
      );
    }

    // 重新获取当前月份的价格数据
    await updateCalendarData(new Date(batchUpdateForm.value.startDate));

    ElMessage.success("批量更新价格成功");
    dialogVisible.value = false;
  } catch (error) {
    console.error("批量更新房价失败:", error);
    ElMessage.error("批量更新房价失败");
  }
};

onMounted(async () => {
  updateCalendarData(new Date());
  await fetchRoomTypes();
});
</script>

<style scoped>
.date {
  margin-left: 15px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

:deep(.el-calendar-table) {
  td {
    height: auto;
    min-height: 120px;
    padding: 0;
  }

  .el-calendar-day {
    height: 100%;
    padding: 0;
    min-height: inherit;
  }
}

.drawer-content {
  padding: 20px;

  .selected-date {
    margin-bottom: 20px;
    font-weight: bold;
  }

  .price-item {
    margin-bottom: 15px;
  }

  .drawer-footer {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 20px;
    background-color: #fff;
    border-top: 1px solid #dcdfe6;
    text-align: right;

    .el-button {
      margin-left: 8px;
    }
  }
}

.dialog-footer {
  text-align: right;
}
</style>
